package org.squirrel.modules.system.auth.request;

import org.squirrel.modules.system.auth.enums.ExAuthThridSource;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.UrlBuilder;
@Slf4j
public class YuezyzwAuthRequest extends BaseAuthRequest{
	public YuezyzwAuthRequest(AuthConfig config) {
		super(config, ExAuthThridSource.YUEZYZW);
	}

	public YuezyzwAuthRequest(AuthConfig config, AuthStateCache authStateCache) {
		super(config, ExAuthThridSource.YUEZYZW, authStateCache);
	}
	
	@Override
	public String authorize(String state) {
		return UrlBuilder.fromBaseUrl(source.authorize())
				.queryParam("client_id", config.getClientId())
				.queryParam("response_type", "code")
				.queryParam("scope", "all")
				.queryParam("redirect_uri", config.getRedirectUri())
				.queryParam("state", getRealState(state)).build();
	}
	
	protected String accessTokenUrl(String code) {
		return UrlBuilder.fromBaseUrl(source.accessToken())
				.queryParam("client_id", config.getClientId())
				.queryParam("grant_type", "authorization_code")
				.queryParam("redirect_uri", config.getRedirectUri())
				.queryParam("code", code)
				.queryParam("client_secret", config.getClientSecret()).build();
	}
	
	@Override
	protected AuthToken getAccessToken(AuthCallback authCallback) {
		String response = doPostAuthorizationCode(authCallback.getCode());
		JSONObject resData = JSONObject.parseObject(response);
		log.info("检查响应结果:{}",resData);
		checkResponseEquals(resData.getString("status"),"0");
		
		JSONObject accessTokenObject = resData.getJSONObject("data");
		
		return AuthToken.builder()
				.accessToken(accessTokenObject.getString("access_token"))
				.expireIn(accessTokenObject.getIntValue("expires_in"))
				.userId(accessTokenObject.getString("userid"))
				.refreshToken(accessTokenObject.getString("token_type")).build();
	}
	
	@Override
	protected AuthUser getUserInfo(AuthToken authToken) {
		String response = doPostUserInfo(authToken);
		JSONObject resData = JSONObject.parseObject(response);
		log.info("获取第三方用户资料:{}",resData);
		checkResponseEquals(resData.getString("status"),"0");
		
		JSONObject userInfoObject = resData.getJSONObject("data");
		
		return AuthUser.builder().rawUserInfo(userInfoObject)
				.uuid(userInfoObject.getString("userId"))
				.username(userInfoObject.getString("userId"))
				.nickname(userInfoObject.getString("name"))
				.token(authToken).source(source.toString()).build();
	}

}
